package com.yy.web.pm.patrol.service.Impl;

import cn.hutool.core.date.DateTime;
import com.yy.web.pm.alarm.domain.AlarmDate;
import com.yy.web.pm.alarm.mapper.AlarmDateMapper;
import com.yy.web.pm.billboard.mapper.BillboardDataMapper;
import com.yy.web.pm.billboardRemove.domain.BillboardRemove;
import com.yy.web.pm.billboardRemove.mapper.BillboardRemoveMapper;
import com.yy.web.pm.operateExamine.domain.ExamineOperate;
import com.yy.web.pm.operateExamine.mapper.ExamineOperateMapper;
import com.yy.web.pm.patrol.dto.*;
import com.yy.web.pm.patrol.domain.PeoplePatrolHistory;
import com.yy.web.pm.patrol.service.FileStorageService;
import com.yy.web.pm.shopPeople.domain.ShopPeople;
import com.yy.web.pm.shopPeople.mapper.ShopPeopleMapper;
import com.yy.web.pm.until.UserNotFoundException;
import com.yy.web.pm.user.domain.User;
import com.yy.web.pm.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.yy.web.pm.patrol.mapper.PeoplePatrolMapper;
import com.yy.web.pm.patrol.domain.PeoplePatrol;
import com.yy.web.pm.patrol.service.PeoplePatrolService;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.yy.web.pm.alarm.service.Impl.AlarmDateServiceImpl.extractOpenId;

@Service
@Slf4j
public class PeoplePatrolServiceImpl implements PeoplePatrolService {

    @Resource
    private PeoplePatrolMapper peoplePatrolMapper;
    @Autowired
    private PeoplePatrolHistoryServiceImpl peoplePatrolHistoryService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ExamineOperateMapper examineOperateMapper;
    @Autowired
    private AlarmDateMapper alarmDateMapper;
    @Autowired
    private BillboardRemoveMapper billboardRemoveMapper;
    @Autowired
    private BillboardDataMapper billboardDataMapper;
    @Autowired
    private ShopPeopleMapper shopPeopleMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return peoplePatrolMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(PeoplePatrol record) {
    // 检查record中的图片列表是否为空
        if (!record.getImage().isEmpty()) {
            String string = record.getImage().stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.joining(","));
            record.setPartrolImages(string);
        }
        // record.setPartrolImages(record.getImage());
        record.setPartrolProgress("0");//新增默认为未处理
        record.setPartrolExaim("0");//新增默认为提交
        record.setPartrolData("0");//设置为巡检数据
        User user = getUser();
        record.setUserId(Math.toIntExact(user.getId()));
        return peoplePatrolMapper.insert(record);
    }

    @Override
    public int insertSelective(PeoplePatrol record) {
        return peoplePatrolMapper.insertSelective(record);
    }

    @Override
    public PeoplePatrol selectByPrimaryKey(Integer id) {
        return peoplePatrolMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(PeoplePatrol record) {
        return peoplePatrolMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(PeoplePatrol record) {
        //巡检处理
        recordDate(record);
        return peoplePatrolMapper.updateByPrimaryKey(record);
    }

    private void recordDate(PeoplePatrol record) {
        //如果是巡检合格，那么记录存档
        if (record.getPartrolProgress().equals("3")) {
            PeoplePatrolHistory history = new PeoplePatrolHistory();
            history.setPartrolId(String.valueOf(record.getId()));
            history.setCreatedTime(new Date());
            history.setPartrolPerpleItem(record.getPatrolPeople());
            history.setPartrolTimeItem(record.getPartrolTime());
            history.setPartrolAddressItem(record.getPartrolAddress());
            history.setPartrolImagesItem(record.getPartrolImages());
            peoplePatrolHistoryService.insert(history);
        } else if (record.getPartrolType().contains("告警")) {
            //     处理告警
            peoplePatrolMapper.updateByPrimaryKey(record);
            //将告警数据状态改为告警
            AlarmDate alarmDate = new AlarmDate().setAlarmState("4");
            ;
            alarmDateMapper.updateByPrimaryKey(alarmDate);
            //操作记录
            recordOperate(examineOperateMapper, record);
        } else if (record.getPartrolType().contains("隐患")) {
            //商家发送给巡检员的记录，整改完成后巡检员巡检
            //     处理商家记录
            peoplePatrolMapper.updateByPrimaryKey(record);
            if (record.getPartrolProgress().equals("1")) {
                AlarmDate alarmDate = new AlarmDate().setAlarmState("6");
                ;
                alarmDateMapper.updateByPrimaryKey(alarmDate);
                //操作记录
                recordOperate(examineOperateMapper, record);
            }
            throw new UserNotFoundException("整改不合格");
        } else if (record.getPartrolType().contains("拆除")) {
            //     处理拆除
            peoplePatrolMapper.updateByPrimaryKey(record);
            //将告警数据状态改为拆除
            AlarmDate alarmDate = new AlarmDate().setAlarmState("5");
            alarmDateMapper.updateByPrimaryKey(alarmDate);
            //操作记录
            recordOperate(examineOperateMapper, record);
        }
    }

    /**
     * @param examineOperateMapper:
     * @param patrol:
     * @Title:recordOperate
     * @Description: 方法描述:操作记录
     */


    private void recordOperate(ExamineOperateMapper examineOperateMapper, PeoplePatrol patrol) {
        User user = userMapper.selectByPrimaryKey(Long.valueOf(patrol.getUserId()));
        ExamineOperate operate = new ExamineOperate()
                .setExaminePeople(user.getUsername())//审核人
                .setEventId(patrol.getId())//审核任务id
                .setExamineTime(DateTime.now())//审核时间
                .setExamineType(patrol.getPartrolType());//审核告警类型
        if (patrol.getPartrolProgress().equals("1")) {
            operate.setExamineOperate("合格");//审核状态
        }
        operate.setExamineOperate("不合格");//审核状态
        examineOperateMapper.insert(operate);
    }

    /**
     * @param patrol:
     * @Title:selectListAll
     * @Description: 方法描述:巡检信息
     */
    @Override
    public List<PeoplePatrol> selectListAll(PeoplePatrol patrol) {
        return peoplePatrolMapper.selectListAll(patrol);
    }

    @Override
    public List<PatroDto> selectShowList(PatroDto patrol) {
        User user = getUser();
        return peoplePatrolMapper.selectShowList(patrol, user.getId());
    }

    private User getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String openId = extractOpenId(authentication.getName());
        User user = userMapper.getUserByOpenId(openId);//获取当前用户信息
        return user;
    }

    @Override
    public List<PatroDto> urgent(PatroDto patrol) {
        User user = getUser();
        return peoplePatrolMapper.SelectUrgent(patrol, user.getId());
    }

    //新增拆除
    @Override
    public int insertRemoveAll(BillboardRemove billboardRemove) {
        //先新增拆除，后删除广告牌
        String beforeImage = billboardRemove.getRemoveBeforeImages().stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.joining(","));
        String aftetImage = billboardRemove.getRemoveAfterImages().stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.joining(","));
        billboardRemove.setRemoveBeforeImage(aftetImage);
        billboardRemove.setRemoveAfterImage(beforeImage);
        billboardRemoveMapper.insert(billboardRemove);
        return shopPeopleMapper.updateByPrimaryKey(new ShopPeople().setShopIsjudge("1"));
    }

    @Override
    public List<PatroDto> selectPatrolList(PatrolDto patrol) {
        User user = getUser();
        patrol.setUserId(Math.toIntExact(user.getId()));
        patrol.setUserId(Math.toIntExact(user.getId()));
        return peoplePatrolMapper.selectPatrolList(patrol);
    }

    @Override
    public List<PeoplePatrol> selectAlarmList(PeoplePatrol patrol) {
        User user = getUser();
        patrol.setUserId(Math.toIntExact(user.getId()));
        return peoplePatrolMapper.selectAlarmList(patrol);
    }
//巡检列表消息接口
    @Override
    public List<PatroLMessage> selectPatrolMessage(PatroLMessage patrol) {
        return peoplePatrolMapper.selectPatrolMessage(patrol);
    }

    @Override
    public BIllboardRemoveDto selectRemoveInfo(String shopId) {
        return peoplePatrolMapper.selectRemoveInfo(shopId);
    }

}
